package com.common.context;

import org.springframework.util.Assert;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class UserContextHolder {

    private static final ThreadLocal<UserContext> USERS_CONTEXT_THREAD_LOCAL = new ThreadLocal<>();

    static void setContext(UserContext usersContext) {
        Assert.notNull(usersContext, "usersContext is null");
        USERS_CONTEXT_THREAD_LOCAL.set(usersContext);
    }

    public static UserContext getContext() {
        if (USERS_CONTEXT_THREAD_LOCAL.get() == null){
            setContext(new UserContext());
        }
        return USERS_CONTEXT_THREAD_LOCAL.get();
    }

    public static void clear() {
        // 避免内存泄漏 清除子线程的引用
        getContext().clear();
        // 清除父线程的引用
        USERS_CONTEXT_THREAD_LOCAL.remove();
    }

}
